
package net.swa.dewei.service.ws.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebParam;
import javax.jws.WebService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.StringType;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import net.swa.dewei.beans.entity.DingDan;
import net.swa.dewei.beans.entity.DingDanCard;
import net.swa.dewei.beans.entity.DingDanCardGoods;
import net.swa.dewei.beans.entity.FuwuZhan;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.entity.Merchants;
import net.swa.dewei.beans.entity.MerchantsLog;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.dewei.beans.vo.GroupAndMaxId;
import net.swa.dewei.beans.vo.StatisMendian;
import net.swa.dewei.beans.vo.VoBackModel;
import net.swa.dewei.beans.vo.VoBackObj;
import net.swa.dewei.beans.vo.VoDingDanCard;
import net.swa.dewei.beans.vo.VoFuwuzhan;
import net.swa.dewei.beans.vo.VoListPage;
import net.swa.dewei.beans.vo.VoMaxIdStateCount;
import net.swa.dewei.service.ws.DeweiService;
import net.swa.system.beans.entity.Dict;
import net.swa.system.beans.entity.User;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.system.util.SysConst;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.EncryptTool;

@WebService(endpointInterface = "net.swa.dewei.service.ws.DeweiService")
@Service("deweiService")
public class DeweiServiceImpl extends HibernateDaoSupport implements DeweiService
{
    private final Logger log = Logger.getLogger(DeweiServiceImpl.class);

    @Override
    public GroupAndMaxId queryGroupMax(Long dingdanId , String state , String token , String mac)
    {
        GroupAndMaxId r = new GroupAndMaxId();
        if (checkAccess(token, mac))
        {
            if (StringUtils.isBlank(state))
            {
                state = BuzConst.DINGDAN_STATES0;
            }
            Session session = getOpenSession();
            StringBuilder sql = new StringBuilder();
            if (null == dingdanId)
            {
                dingdanId = 0l;
            }
            FuwuZhan fuwuzhan = null;
            Long fuwuzhanId = getIdFromToken(token, mac);
            if (null != fuwuzhanId)
            {
                fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, fuwuzhanId);
                if (null != fuwuzhan)
                {
                    sql.append("select  t.state,count(t.id) as sum,t.changeType    from  t_DingDan t left join  t_MenDian m on m.id=t.mendianId   where t.id>:dingdanId and t.changeType=:changeType and  t.state=:state  ");
                    if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                    {
                        sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                        if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                        {
                            sql.append(" or (");
                            sql.append("  t.province like :province");
                            if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                            {
                                sql.append(" and t.city like :city");
                                if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                                {
                                    sql.append(" and t.town like :town");
                                }
                            }
                            sql.append(" ))");
                        }
                    }
                    sql.append(" GROUP BY changeType,state");
                }
                else
                {
                    r.setSuccess(false);
                    r.setMessage("查询当前服务站信息失败");
                    return r;
                }
            }
            else
            {
                sql.append("select  state,count(id) as sum ,changeType   from t_dingdan  where id>:dingdanId and changeType=:changeType and state=:state  GROUP BY changeType, state ");
            }

            SQLQuery ss = (SQLQuery) session.createSQLQuery(sql.toString()).addScalar("state", StringType.INSTANCE).addScalar("sum", StandardBasicTypes.INTEGER).addScalar("changeType", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(VoMaxIdStateCount.class));
            if (null != fuwuzhan)
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    ss.setLong("fuwuzhanId", fuwuzhan.getId());
                    ss.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        ss.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            ss.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
            ss.setString("state", state);
            ss.setLong("dingdanId", 0l);
            ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_SM);
            VoMaxIdStateCount vo = (VoMaxIdStateCount) ss.uniqueResult();
            if (null == vo)
            {
                vo = new VoMaxIdStateCount();
                vo.setChangeType(BuzConst.DINGDAN_CHANGE_TYPE_SM);
                vo.setState(state);
                vo.setNewSum(0);
                vo.setSum(0);
            }
            else
            {
                vo.setNewSum(0);
                if (0l != dingdanId)
                {
                    ss.setLong("dingdanId", dingdanId);
                    ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_SM);
                    VoMaxIdStateCount vo3 = (VoMaxIdStateCount) ss.uniqueResult();
                    if (null != vo3)
                    {
                        if (null != vo3.getSum())
                        {
                            vo.setNewSum(vo3.getSum());
                        }
                    }
                }
                else
                {
                    vo.setNewSum(vo.getSum());
                }
            }
            ss.setLong("dingdanId", 0l);
            ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_MD);
            VoMaxIdStateCount vo2 = (VoMaxIdStateCount) ss.uniqueResult();
            if (null == vo2)
            {
                vo2 = new VoMaxIdStateCount();
                vo2.setChangeType(BuzConst.DINGDAN_CHANGE_TYPE_MD);
                vo.setState(state);
                vo2.setNewSum(0);
                vo2.setSum(0);
            }
            else
            {
                vo2.setNewSum(0);
                if (0l != dingdanId)
                {
                    ss.setLong("dingdanId", dingdanId);
                    ss.setString("changeType", BuzConst.DINGDAN_CHANGE_TYPE_MD);
                    VoMaxIdStateCount vo4 = (VoMaxIdStateCount) ss.uniqueResult();
                    if (null != vo4)
                    {
                        if (null != vo4.getSum())
                        {
                            vo2.setNewSum(vo4.getSum());
                        }
                    }
                }
                else
                {
                    vo2.setNewSum(vo2.getSum());
                }
            }
            r.setNearChange(vo2);
            r.setManuChange(vo);
            r.setSuccess(true);
            ss = session.createSQLQuery("select max(id) as maxid  from t_dingdan");
            Long maxid = Long.parseLong(ss.uniqueResult().toString());
            r.setCurrentMaxId(maxid);
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            r.setAuthError();
        }
        return r;
    }

    @Override
    public VoListPage<DingDan> queryDingdansPage2(String customerName , String customerTel , String mendianName , String dingDanUid , String state , String changeType , Long currentId , int pageSize , String token , String mac)
    {
        VoListPage<DingDan> json = new VoListPage<DingDan>();
        if (checkAccess(token, mac))
        {
            FuwuZhan fuwuzhan = null;
            Session session = getOpenSession();
            Long fuwuZhanId = getIdFromToken(token, mac);
            if (null != fuwuZhanId)
            {
                fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, fuwuZhanId);
            }

            List<DingDan> list = new ArrayList<DingDan>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            sql
                    .append("select t.address,t.changeType,t.chexingId, t.chexingName,t.city,t.crateDate,t.dianchiId,dingDanUid, t.id,t.imageUrl, t.kehuName,t.blat,t.blng,t.lat,t.lng,t.lxTel,m.lxrTel  as  menDianTel,m.address  as  mendianAddr,t.mendianId,m.lxr as  mendianLxr, m.name as mendianName, t.pinPai, t.price, t.province, t.state, t.time, t.town, t.updateDate, t.userId, t.xingHao,t.detailInfo,t.licheng,t.zhongliang,t.marketPrice,t.serverPrice  from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  where 1=1 ");
            countsql.append("select  count(*)  as counNum  from  t_DingDan t  left join  t_MenDian m on m.id=t.mendianId  where 1=1 ");

            if (!StringUtils.isBlank(dingDanUid))
            {
                sql.append(" and t.dingDanUid like :dingDanUid");
                countsql.append(" and t.dingDanUid like :dingDanUid");
            }
            if (!StringUtils.isBlank(customerName))
            {
                sql.append(" and t.kehuName like :customerName");
                countsql.append(" and t.kehuName like :customerName");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                sql.append(" and t.lxTel like :customerTel");
                countsql.append(" and t.lxTel like :customerTel");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                sql.append(" and m.name like :mendianName");
                countsql.append(" and m.name like :mendianName");
            }
            if (!StringUtils.isBlank(state))
            {
                sql.append(" and t.state=:state");
                countsql.append(" and t.state=:state");
            }
            if (!StringUtils.isBlank(changeType))
            {
                sql.append(" and t.changeType=:changeType");
                countsql.append(" and t.changeType=:changeType");
            }

            if (null != fuwuzhan)
            {
                sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                countsql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    sql.append(" or (t.changeType<>'附近门店更换' and  ");
                    countsql.append(" or (t.changeType<>'附近门店更换' and  ");
                    sql.append("  t.province like :province");
                    countsql.append("  t.province like :province");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        sql.append(" and t.city like :city");
                        countsql.append(" and t.city like :city");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            sql.append(" and t.town like :town  ");
                            countsql.append(" and t.town like :town ");
                        }
                    }
                    sql.append(" ))");
                    countsql.append(" ))");
                }
            }
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);//"select count(*) as counNum from (" + sql.toString() + ") as d"
            if (!StringUtils.isBlank(dingDanUid))
            {
                query.setString("dingDanUid", "%" + dingDanUid + "%");
            }
            if (!StringUtils.isBlank(customerName))
            {
                query.setString("customerName", "%" + customerName.trim() + "%");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                query.setString("customerTel", "%" + customerTel.trim() + "%");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                query.setString("mendianName", "%" + mendianName.trim() + "%");
            }
            if (!StringUtils.isBlank(state))
            {
                query.setString("state", state);
            }
            if (!StringUtils.isBlank(changeType))
            {
                query.setString("changeType", changeType);
            }
            if (null != fuwuzhan)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);

            if (null != currentId)
            {
                sql.append(" and t.id<:currentId ");
            }
            query = session.createSQLQuery(sql.toString() + " order by id desc").addEntity(DingDan.class);
            if (!StringUtils.isBlank(dingDanUid))
            {
                query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
            }
            if (!StringUtils.isBlank(customerName))
            {
                query.setString("customerName", "%" + customerName.trim() + "%");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                query.setString("customerTel", "%" + customerTel.trim() + "%");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                query.setString("mendianName", "%" + mendianName.trim() + "%");
            }
            if (!StringUtils.isBlank(state))
            {
                query.setString("state", state);
            }
            if (!StringUtils.isBlank(changeType))
            {
                query.setString("changeType", changeType);
            }
            if (null != fuwuzhan)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);

                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            list = query.list();
            if (null != list && list.size() > 0)
            {
                for (DingDan o : list)
                {
                    if (!StringUtils.isBlank(o.getCrateDate()))
                    {
                        o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                    }
                }
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);

                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            json.setResult(list);
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoBackObj updateOrderStatus(final Long id , final String status , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Query query = session.createQuery("update DingDan set state=:state  where id=:id");
            query.setLong("id", id);
            query.setString("state", status);
            Transaction tx = session.beginTransaction();
            query.executeUpdate();
            tx.commit();
            if (session.isOpen())
            {
                session.close();
            }
            obj.setCheckSuccess();
        }
        else
        {
            log.debug("ws ，updateOrderStatus 非法调用。");
            obj.setCheckError();
        }
        return obj;
    }

    @Override
    public VoBackObj updateAssign(final Long id , final Long shopId , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Query query = session.createQuery("update DingDan set mendianId=:mendianId,state=:state  where id=:id");
            query.setLong("id", id);
            query.setLong("mendianId", shopId);
            query.setString("state", "2");
            Transaction tx = session.beginTransaction();
            query.executeUpdate();
            tx.commit();
            if (session.isOpen())
            {
                session.close();
            }
            obj.setCheckSuccess();
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    public VoBackObj addMenDian(MenDian model , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Transaction tx = null;
            Long fid;
            try
            {
                fid = getIdFromToken(token, mac);
                Query q = null;
                if (null != fid)
                {
                    if (null != model.getFuwuzhanId())
                    {
                        log.debug("the fuwuzhanId from  token  is  " + fid + "  model  model.getFuwuzhanId() is " + model.getFuwuzhanId());
                    }
                    else
                    {
                        log.debug("the fuwuzhanId from  token  is " + fid + "  model  model.getFuwuzhanId() is null  i give it.");
                        model.setFuwuzhanId(fid);
                    }
                    model.setFuwuzhanId(fid);
                    if ((!StringUtils.isBlank(model.getProvince())))
                    {
                        String sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 ) or (a.province like :province1))";
                        if (!StringUtils.isBlank(model.getCity()) && (!(model.getCity()).equals(model.getProvince())))
                        {
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                if ((model.getCity()).equals(model.getTown()))
                                {
                                    sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1  and f.town like :town1 ) or (a.province like :province1  and a.town like :town1))";
                                }
                                else
                                {
                                    sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 and f.city like :city1 and f.town like :town1 ) or (a.province like :province1 and a.city like :city1 and a.town like :town1))";
                                }
                            }
                            else
                            {
                                sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 and f.city like :city1) or (a.province like :province1 and a.city like :city1))";
                            }
                        }
                        else if (!StringUtils.isBlank(model.getTown()))
                        {
                            sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1  and f.town like :town1 ) or (a.province like :province1  and a.town like :town1))";
                        }

                        q = session.createSQLQuery(sql).addScalar("countNum", StandardBasicTypes.INTEGER);
                        q.setLong("id", fid);
                        String province = model.getProvince();
                        q.setString("province1", province.substring(0, (province.length() - 1)) + "%");

                        if (!StringUtils.isBlank(model.getCity()) && (!(model.getCity()).equals(model.getProvince())))
                        {
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                if ((model.getCity()).equals(model.getTown()))
                                {
                                    log.debug("特殊位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                }
                                else
                                {
                                    log.debug("普通位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                    q.setString("city1", model.getCity().substring(0, (model.getCity().length() - 1)) + "%");
                                }
                                q.setString("town1", model.getTown().substring(0, (model.getTown().length() - 1)) + "%");
                            }
                            else
                            {
                                log.debug("没有区的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                q.setString("city1", model.getCity().substring(0, (model.getCity().length() - 1)) + "%");
                            }
                        }
                        else if (!StringUtils.isBlank(model.getTown()))
                        {
                            log.debug("没有市的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                            q.setString("town1", model.getTown().substring(0, (model.getTown().length() - 1)) + "%");
                        }
                        else
                        {
                            log.debug("只有省的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                        }
                        int totalCount = (Integer) q.uniqueResult();
                        if (totalCount < 1)
                        {
                            obj.setSuccess(false);
                            obj.setErrorCode("2");//拒绝
                            obj.setMessage("该区域不允许您开店！");
                            return obj;
                        }
                    }
                    else
                    {
                        obj.setSuccess(false);
                        obj.setMessage("请标注您开店的位置，确保包含位置信息");
                        obj.setErrorCode("3");//传入参数不合法
                        return obj;
                    }
                    model.setCrateDate(DateUtils.getCurrDate(null));
                    model.setStatus(BuzConst.STATUS_YES);
                    //                    if (model.getChargeStation())
                    //                    {
                    //                        model.setWxid(null);
                    //                    }
                    tx = session.beginTransaction();
                    if (!StringUtils.isBlank(model.getWxid()))
                    {
                        //微信必须不是门店才可以指定
                        q = session.createQuery("from WeixinInfo where mendian=:mendian and id=:id ");
                        q.setBoolean("mendian", false);
                        q.setString("id", model.getWxid());
                        List l = q.list();
                        if (null != l && l.size() > 0)
                        {
                            WeixinInfo wx = (WeixinInfo) l.get(0);
                            wx.setMendian(true);
                            session.update(wx);
                        }
                        else
                        {
                            obj.setSuccess(false);
                            obj.setMessage("该微信已经被他人指定请重新选择。");
                            if (null != tx)
                            {
                                tx.rollback();
                            }
                            return obj;
                        }
                    }
                    session.save(model);
                    obj.setCheckSuccess();
                    tx.commit();
                }
                else
                {
                    obj.setCheckError();
                }
            }
            catch (Exception e)
            {
                if (null != tx)
                {
                    tx.rollback();
                }
                if (log.isDebugEnabled())
                {
                    log.debug("新增门店异常：" + e);
                }
                obj.setSuccess(false);
                obj.setErrorCode("-1");//系统异常
                obj.setMessage("系统异常");
            }
            finally
            {
                if (session.isOpen())
                {
                    session.close();
                }
            }
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    @Override
    public VoBackObj delete(Long[] ids , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Transaction tx = session.beginTransaction();
            try
            {
                for (int i = 0; i < ids.length; i++)
                {
                    Query query = null;
                    MenDian m = (MenDian) session.get(MenDian.class, ids[i]);
                    if (null != m)
                    {
                        String wxid = m.getWxid();
                        if (!StringUtils.isBlank(wxid))
                        {
                            query = session.createQuery("update WeixinInfo set mendian=:mendian where id=:id");
                            query.setBoolean("mendian", false);
                            query.setString("id", wxid);
                            query.executeUpdate();
                        }
                    }
                    query = session.createQuery("update MenDian set wxid=null, status=" + BuzConst.STATUS_NO + " where id=:id");
                    query.setLong("id", ids[i]);
                    query.executeUpdate();
                }
                tx.commit();
            }
            catch (Exception e)
            {
                tx.rollback();
                obj.setCheckSuccess();
                if (log.isDebugEnabled())
                {
                    log.debug("删除出现系统异常");
                }
            }
            finally
            {
                if (session.isOpen())
                {
                    session.close();
                }
            }
            obj.setCheckSuccess();
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    @Override
    public VoListPage<MenDian> queryMendianPage(String name , String nickname , Long currentId , int pageSize , String token , String mac) throws Exception
    {
        VoListPage<MenDian> json = new VoListPage<MenDian>();
        Long fuwuzhanId = getIdFromToken(token, mac);
        if (null != fuwuzhanId)
        {
            if (log.isDebugEnabled())
            {
                log.debug("传入参数 nickname is" + nickname + ", currentId is " + currentId + ",pageSize is " + pageSize);
            }
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            countsql.append("select count(1) as counNum  from  t_MenDian m join t_FuwuZhan f on f.id=m.fuwuzhanId left join t_WeixinInfo  w on w.openid=m.wxid  where 1=1 ");
            sql.append("select m.address, m.city, m.crateDate, m.detailInfo, m.fuwuzhanId, f.name as fuwuzhanName, m.id, m.imageUrl, m.latitude, m.longitude, m.lxr, m.lxrTel, m.name, w.nickname, m.province, m.town, m.updateDate, m.wxid,m.chargeStation,m.chargImageUrl,m.weixiu,m.xiaoshou,m.mobiCharge,m.mendianNo  from  t_MenDian m left join t_FuwuZhan f on f.id=m.fuwuzhanId  left join t_WeixinInfo   w  on w.openid=m.wxid   where 1=1 ");

            sql.append(" and m.status=" + BuzConst.STATUS_YES + " ");
            countsql.append(" and m.status=" + BuzConst.STATUS_YES + " ");

            if (!StringUtils.isBlank(nickname))
            {
                sql.append(" and w.nickname  like :nickname");
                countsql.append(" and w.nickname  like :nickname");
            }
            if (null != fuwuzhanId)
            {
                sql.append(" and m.fuwuzhanId= :fuwuzhanId ");
                countsql.append(" and m.fuwuzhanId= :fuwuzhanId ");
            }
            if (!StringUtils.isBlank(name))
            {
                sql.append(" and m.name  like :name");
                countsql.append(" and m.name  like :name");
            }
            if (null != currentId)
            {
                sql.append(" and m.id<:currentId ");
            }
            Session session = getOpenSession();
            query = session.createSQLQuery(sql.toString() + "  order  by m.id  desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("address", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("latitude",
                    StandardBasicTypes.DOUBLE).addScalar("longitude", StandardBasicTypes.DOUBLE).addScalar("lxr", StandardBasicTypes.STRING).addScalar("lxrTel", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("nickname", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("wxid", StandardBasicTypes.STRING).addScalar("chargeStation",
                    StandardBasicTypes.BOOLEAN).addScalar("mobiCharge", StandardBasicTypes.BOOLEAN).addScalar("chargImageUrl", StandardBasicTypes.STRING).addScalar("weixiu", StandardBasicTypes.BOOLEAN).addScalar("xiaoshou", StandardBasicTypes.BOOLEAN).addScalar("mendianNo", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(MenDian.class));

            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            List<MenDian> list = query.list();
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);
            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);
            json.setResult(list);
            if (null != list && list.size() > 0)
            {
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);
                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS queryMendianPage 方法调用失败，token校验失败");
            }
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoBackObj updateMendian(MenDian model , String oldWxid , String token , String mac)
    {
        VoBackObj json = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Transaction tx = null;
            Query q = null;
            Long fid;
            try
            {
                fid = getIdFromToken(token, mac);
                if (null != model.getFuwuzhanId())
                {
                    log.debug("the fuwuzhanId from  token  is  " + fid + "  model  model.getFuwuzhanId() is " + model.getFuwuzhanId());
                }
                else
                {
                    log.debug("the fuwuzhanId from  token  is " + fid + "  model  model.getFuwuzhanId() is null  i give it.");
                    model.setFuwuzhanId(fid);
                }
                model.setFuwuzhanId(fid);
                if (null != fid)
                {
                    if (!StringUtils.isBlank(model.getProvince()))
                    {
                        String sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 ) or (a.province like :province1))";
                        if (!StringUtils.isBlank(model.getCity()) && (!(model.getCity()).equals(model.getProvince())))
                        {
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                if ((model.getCity()).equals(model.getTown()))
                                {
                                    sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1  and f.town like :town1 ) or (a.province like :province1  and a.town like :town1))";
                                }
                                else
                                {
                                    sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 and f.city like :city1 and f.town like :town1 ) or (a.province like :province1 and a.city like :city1 and a.town like :town1))";
                                }
                            }
                            else
                            {
                                sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1 and f.city like :city1) or (a.province like :province1 and a.city like :city1))";
                            }
                        }
                        else if (!StringUtils.isBlank(model.getTown()))
                        {
                            sql = "select count(*) as countNum  from t_FuwuZhan f join t_FuwuZhanArea a on f.id=a.fuwuzhanId where f.id=:id and ( (f.province like :province1  and f.town like :town1 ) or (a.province like :province1  and a.town like :town1))";
                        }
                        q = session.createSQLQuery(sql).addScalar("countNum", StandardBasicTypes.INTEGER);
                        q.setLong("id", fid);
                        String province = model.getProvince();
                        q.setString("province1", province.substring(0, (province.length() - 1)) + "%");

                        if (!StringUtils.isBlank(model.getCity()) && (!(model.getCity()).equals(model.getProvince())))
                        {
                            if (!StringUtils.isBlank(model.getTown()))
                            {
                                if ((model.getCity()).equals(model.getTown()))
                                {
                                    log.debug("特殊位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                }
                                else
                                {
                                    log.debug("普通位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                    q.setString("city1", model.getCity().substring(0, (model.getCity().length() - 1)) + "%");
                                }
                                q.setString("town1", model.getTown().substring(0, (model.getTown().length() - 1)) + "%");
                            }
                            else
                            {
                                log.debug("没有区的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                                q.setString("city1", model.getCity().substring(0, (model.getCity().length() - 1)) + "%");
                            }
                        }
                        else if (!StringUtils.isBlank(model.getTown()))
                        {
                            log.debug("没有市的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                            q.setString("town1", model.getTown().substring(0, (model.getTown().length() - 1)) + "%");
                        }
                        else
                        {
                            log.debug("只有省的位置：" + model.getProvince() + "," + model.getCity() + "," + model.getTown());
                        }
                        int totalCount = (Integer) q.uniqueResult();
                        if (totalCount < 1)
                        {
                            json.setSuccess(false);
                            json.setErrorCode("2");//拒绝
                            json.setMessage("该区域不允许您开店！");
                            return json;
                        }
                    }
                    else
                    {
                        json.setSuccess(false);
                        json.setErrorCode("3");
                        json.setMessage("请标注您开店的位置，确保包含省市信息");
                        return json;
                    }
                    model.setStatus(BuzConst.STATUS_YES);
                    model.setUpdateDate(DateUtils.getCurrDate(null));
                    //打开session
                    session = getOpenSession();
                    tx = session.beginTransaction();

                    //                    if (model.getChargeStation())
                    //                    {
                    //                        model.setWxid(null);
                    //                    }

                    if (!StringUtils.isBlank(model.getWxid()))
                    {
                        boolean f = true;
                        if (!StringUtils.isBlank(oldWxid))
                        {
                            if (model.getWxid().equals(oldWxid))
                            {
                                f = false;
                            }
                        }
                        if (f)
                        {
                            //微信必须不是门店才可以指定
                            q = session.createQuery("from WeixinInfo where mendian=:mendian and id=:id ");
                            q.setBoolean("mendian", false);
                            q.setString("id", model.getWxid());
                            List l = q.list();
                            if (null != l && l.size() > 0)
                            {
                                WeixinInfo wx = (WeixinInfo) l.get(0);
                                wx.setMendian(true);
                                session.update(wx);
                                q = session.createQuery("update WeixinInfo set mendian=:mendian where id=:id ");
                                if (!StringUtils.isBlank(oldWxid))
                                {
                                    q.setBoolean("mendian", false);
                                    q.setString("id", oldWxid);
                                    q.executeUpdate();
                                }
                            }
                            else
                            {
                                json.setSuccess(false);
                                json.setErrorCode("2");
                                json.setMessage("该微信已经被他人指定请重新选择。");
                                if (null != tx)
                                {
                                    tx.rollback();
                                }
                                return json;
                            }
                        }
                    }
                    //                    if (model.getChargeStation())
                    //                    {
                    //                        if (!StringUtils.isBlank(oldWxid))
                    //                        {
                    //                            q = session.createQuery("update WeixinInfo set mendian=:mendian where id=:id ");
                    //                            q.setBoolean("mendian", false);
                    //                            q.setString("id", oldWxid);
                    //                            q.executeUpdate();
                    //                        }
                    //                    }
                    session.update(model);
                    json.setCheckSuccess();
                    tx.commit();
                }
                else
                {
                    json.setSuccess(false);
                    json.setErrorCode("404");
                    json.setMessage("查询服务站异常。");
                }
            }
            catch (Exception e)
            {
                if (null != tx)
                {
                    tx.rollback();
                }
                e.printStackTrace();
            }
            finally
            {
                if (session.isOpen())
                {
                    session.close();
                }
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS updateMendian 方法调用失败，token校验失败");
            }
            json.setCheckError();
        }
        return json;
    }

    @Override
    public VoListPage<WeixinInfo> queryWeixinPage(String nickName , String wxid , String currentId , int pageSize , String token , String mac)
    {
        VoListPage<WeixinInfo> json = new VoListPage<WeixinInfo>();
        if (checkAccess(token, mac))
        {

            List<WeixinInfo> list = new ArrayList<WeixinInfo>();
            StringBuilder hql = new StringBuilder().append(" from WeixinInfo  where 1=1 ");
            if (!StringUtils.isBlank(nickName))
            {
                hql.append(" and nickName like :nickName ");
            }
            //打开session
            Session session = getOpenSession();
            Query q = null;
            if (!StringUtils.isBlank(currentId))
            {
                q = session.createQuery(hql.toString() + " where id<:currentId order by desc ");
            }
            else
            {
                q = session.createQuery(hql.toString() + " order by id desc ");
            }

            if (!StringUtils.isBlank(nickName))
            {
                q.setString("nickName", "%" + nickName + "%");
            }
            if (!StringUtils.isBlank(currentId))
            {
                q.setString("currentId", currentId);
            }
            q.setMaxResults(pageSize);
            list = q.list();
            q = session.createQuery("select count(*) " + hql);
            if (!StringUtils.isBlank(nickName))
            {
                q.setString("nickName", "%" + nickName + "%");
            }
            int totalCount = ((Number) (q.iterate().next())).intValue();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);

            if (null != list && list.size() > 0)
            {
                String id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);
                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    log.debug("如果是满的list，认为当期还有下一页，下次如若无查询返回null list");
                    json.setHasNext(true);
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            json.setResult(list);
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoFuwuzhan loginByFuwuzhan(String loginName , String password , String mac)
    {
        VoFuwuzhan result = new VoFuwuzhan();
        FuwuZhan fuwuzhan = null;
        Session session = getOpenSession();
        Query q = session.createQuery(" from User where userid=:userid ");
        q.setString("userid", loginName);
        List<User> ulist = q.list();
        q = session.createQuery(" from FuwuZhan where fuwuzhanId=:fuwuzhanId");
        User loginUser = null;
        if (null != ulist && ulist.size() > 0)
        {
            loginUser = ulist.get(0);

            if (ulist.size() > 1)
            {
                result.setErrorCode("500");
                result.setSuccess(false);
                result.setMessage("ERROR,系统出错");
                log.debug("ERROR 平板端登陆错误,相同的用户名称多个用户");
                return result;
            }
        }
        EncryptTool tool;
        try
        {
            tool = new EncryptTool(loginName);
            if (null != loginUser)
            {
                String psw = tool.encrypt(password);
                log.debug("平板端登陆，loginName is " + loginName + ",password is " + password);
                if (psw.equals(loginUser.getPassword()))// 将登陆页面上的16位进制的密码值转换成byte数组
                {
                    if (null != loginUser.getFuwuzhanId() && SysConst.USER_TYPE_FUWUZHAN == loginUser.getUserType())
                    {
                        fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, loginUser.getFuwuzhanId());
                        //                        if (null != fuwuzhan)
                        //                        {
                        //                            q.setLong("fuwuzhanId", loginUser.getFuwuzhanId());
                        //                            List<FuwuZhanArea> areas = q.list();
                        //                            log.debug("根据服务站id 查询允许开店的区域信息：");
                        //                            for (int i = 0; i < areas.size(); i++)
                        //                            {
                        //                                log.debug(i + " ：" + areas.get(i).toString());
                        //                            }
                        //                            log.debug("根据服务站id 查询允许开店的区域信息结束。");
                        //                            fuwuzhan.setLimitAreas(areas);
                        //                        }

                        if (null != fuwuzhan)
                        {
                            if (!StringUtils.isBlank(fuwuzhan.getMac()))
                            {
                                if (mac.equals(fuwuzhan.getMac()) || "admin".equals(fuwuzhan.getMac()))
                                {
                                    fuwuzhan.setToken(generateToken(loginUser.getFuwuzhanId(), mac));
                                    result.setErrorCode("200");
                                    result.setSuccess(true);
                                    result.setFuwuzhan(fuwuzhan);
                                    result.setMessage("成功校验后登陆成功");
                                }
                                else
                                {
                                    //                                    fuwuzhan = null;
                                    //                                    result.setFuwuzhan(null);
                                    //                                    result.setErrorCode("500");
                                    //                                    result.setSuccess(false);
                                    //                                    result.setMessage("服务站MAC校验失败");

                                    fuwuzhan.setToken(generateToken(loginUser.getFuwuzhanId(), mac));
                                    result.setErrorCode("200");
                                    result.setSuccess(true);
                                    result.setFuwuzhan(fuwuzhan);
                                    result.setMessage("实际上该账号已经被绑定了");
                                }
                            }
                            else
                            {
                                fuwuzhan.setMac(mac);
                                Transaction tx = session.beginTransaction();
                                session.update(fuwuzhan);
                                tx.commit();
                                fuwuzhan.setToken(generateToken(loginUser.getFuwuzhanId(), mac));
                                result.setErrorCode("200");
                                result.setSuccess(true);
                                result.setFuwuzhan(fuwuzhan);
                                result.setMessage("成功绑定MAC登陆成功");
                            }
                            log.debug("登陆成功，服务站信息为:" + fuwuzhan);
                        }
                    }
                    else
                    {
                        result.setErrorCode("404");
                        result.setMessage(" 非服务站用户");
                        log.debug("平板端登陆,error 非服务站用户，loginName is " + loginName + ",password is " + password);
                    }
                }
                else
                {
                    result.setErrorCode("404");
                    result.setMessage("用户名或密码错误");
                    log.debug("平板端登陆,error 用户名或密码错误，loginName is " + loginName + ",password is " + password);
                }
            }
            else
            {
                result.setErrorCode("404");
                result.setMessage("平板端登陆错误,系统无该用户");
                log.debug("平板端登陆错误,系统无该用户");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (session.isOpen())
            {
                session.close();
            }
        }
        return result;
    }

    @Override
    public VoBackObj resetPassword(String userid , String oldpwd , String password , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            log.debug("平板端更改密码，loginName is " + userid + ",password is " + oldpwd + ",new psw is " + password);
            Session session = getOpenSession();
            Query q = session.createQuery(" from User where userid=:userid");
            q.setString("userid", userid);
            List<User> ulist = q.list();
            User u = null;
            if (null != ulist && ulist.size() > 0)
            {
                u = ulist.get(0);
                if (ulist.size() > 1)
                {
                    log.debug("平板端登陆错误,相同的用户名称多个用户");
                }
            }
            try
            {
                if (null != u)
                {
                    if (SysConst.USER_TYPE_FUWUZHAN == u.getUserType())
                    {
                        EncryptTool tool;
                        tool = new EncryptTool(u.getUserid());
                        String psw = tool.encrypt(oldpwd); // 将页面输入的密码进行加密，跟数据库中的加密密码进行
                        if (psw.equals(u.getPassword()))
                        {
                            Transaction tx = session.beginTransaction();
                            u.setPassword(tool.encrypt(password));
                            session.update(u);
                            tx.commit();
                            obj.setCheckSuccess();
                        }
                        else
                        {
                            obj.setSuccess(false);
                            obj.setErrorCode("2");
                            obj.setMessage("密码输入错误");
                            log.debug("平板端更改密码,密码输入错误，loginName is " + userid + ",password is " + oldpwd + ",new psw is " + password);
                        }
                    }
                    else
                    {
                        obj.setSuccess(false);
                        obj.setErrorCode("2");
                        obj.setMessage("非服务站用户");
                        log.debug("平板端更改密码,用户非服务站用户，loginName is " + userid + ",password is " + oldpwd + ",new psw is " + password);
                    }
                }
            }
            catch (Exception e)
            {
                if (log.isEnabledFor(Level.DEBUG))
                {
                    log.debug("重置密码异常：" + e);
                }
            }
            finally
            {
                if (session.isOpen())
                {
                    session.close();
                }
            }
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    /****
     * 根据机器码和服务站id生成token
     * @param id
     * @param mac
     * @return
     */
    private String generateToken(Long id , String mac)
    {
        String s = null;
        if (StringUtils.isBlank(mac))
        {
            mac = BuzConst.DEFAULT_KEY;
        }
        try
        {
            EncryptTool tool;
            tool = new EncryptTool(mac);
            s = tool.encrypt(id.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        log.debug("id is " + id + ",mac is +" + mac + ",generateToken is " + s);
        return s;
    }

    /****
     * 根据机器码和服务站id生成token
     * @param id
     * @param mac
     * @return
     * @throws Exception 
     */
    private Long getIdFromToken(String token , String mac)
    {
        Long id = null;
        if (StringUtils.isBlank(mac))
        {
            mac = BuzConst.DEFAULT_KEY;
        }
        EncryptTool tool;
        try
        {
            tool = new EncryptTool(mac);
            String sid = tool.decrypt(token);
            id = Long.parseLong(sid);
        }
        catch (Exception e)
        {
            id = null;
            e.printStackTrace();
            if (log.isDebugEnabled())
            {
                log.debug("异常，取得服务站id is " + id);
            }
        }
        return id;
    }

    private boolean checkAccess(String token , String mac)
    {
        Long id = null;
        try
        {
            if (StringUtils.isBlank(mac))
            {
                mac = BuzConst.DEFAULT_KEY;
            }
            EncryptTool tool;
            tool = new EncryptTool(mac);
            String sid = tool.decrypt(token);
            id = Long.parseLong(sid);
        }
        catch (Exception e)
        {
            log.debug("校验出现异常" + e);
            e.printStackTrace();
        }
        if (!StringUtils.isBlank(mac) && (null != id))
        {
            if ("admin".equals(mac))
            {
                return true;//暂时不校验绑定
            }
            else
            {
                String hql = " from FuwuZhan where id=:id and (mac=:mac or mac=:mac2)";
                Session session = getOpenSession();
                Query query = session.createQuery(hql);
                query.setLong("id", id);
                query.setString("mac", mac);
                query.setString("mac2", "admin");
                List<FuwuZhan> fl = (List<FuwuZhan>) query.list();
                if (null != fl && fl.size() > 0)
                {
                    log.debug("from  DB 校验OK");
                    return true;
                }
                else
                {
                    log.debug("from  DB 校验失败");
                    return false;
                }
            }
        }
        else
        {
            log.debug("校验出现异常,校验失败");
            return false;
        }
    }

    @Override
    public VoListPage<MenDian> queryStationPage(String name , String nickname , Long currentId , int pageSize , String token , Boolean isStation , String mac) throws Exception
    {
        VoListPage<MenDian> json = new VoListPage<MenDian>();
        Long fuwuzhanId = getIdFromToken(token, mac);
        if (null != fuwuzhanId)
        {
            if (log.isDebugEnabled())
            {
                log.debug("传入参数 nickname is" + nickname + ", currentId is " + currentId + ",pageSize is " + pageSize);
            }
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            countsql.append("select count(1) as counNum  from  t_MenDian m join t_FuwuZhan f on f.id=m.fuwuzhanId left join t_WeixinInfo  w on w.openid=m.wxid  where 1=1 ");
            sql.append("select m.address, m.city, m.crateDate, m.detailInfo, m.fuwuzhanId, f.name as fuwuzhanName, m.id, m.imageUrl, m.latitude, m.longitude, m.lxr, m.lxrTel, m.name, w.nickname, m.province, m.town, m.updateDate, m.wxid,m.chargeStation,m.chargImageUrl,m.weixiu,m.xiaoshou,m.mobiCharge,m.mendianNo  from  t_MenDian m left join t_FuwuZhan f on f.id=m.fuwuzhanId  left join t_WeixinInfo   w  on w.openid=m.wxid   where 1=1 ");

            sql.append(" and m.status=" + BuzConst.STATUS_YES + " ");
            countsql.append(" and m.status=" + BuzConst.STATUS_YES + " ");

            if (null != isStation)
            {
                sql.append(" and m.chargeStation=" + isStation + " ");
                countsql.append(" and m.chargeStation=" + isStation + " ");
            }

            if (!StringUtils.isBlank(nickname))
            {
                sql.append(" and w.nickname  like :nickname");
                countsql.append(" and w.nickname  like :nickname");
            }
            if (null != fuwuzhanId)
            {
                sql.append(" and m.fuwuzhanId= :fuwuzhanId ");
                countsql.append(" and m.fuwuzhanId= :fuwuzhanId ");
            }
            if (!StringUtils.isBlank(name))
            {
                sql.append(" and m.name  like :name");
                countsql.append(" and m.name  like :name");
            }
            if (null != currentId)
            {
                sql.append(" and m.id<:currentId ");
            }
            Session session = getOpenSession();
            query = session.createSQLQuery(sql.toString() + "  order  by m.id  desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("address", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("latitude",
                    StandardBasicTypes.DOUBLE).addScalar("longitude", StandardBasicTypes.DOUBLE).addScalar("lxr", StandardBasicTypes.STRING).addScalar("lxrTel", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("nickname", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("wxid", StandardBasicTypes.STRING).addScalar("chargeStation",
                    StandardBasicTypes.BOOLEAN).addScalar("mobiCharge", StandardBasicTypes.BOOLEAN).addScalar("chargImageUrl", StandardBasicTypes.STRING).addScalar("weixiu", StandardBasicTypes.BOOLEAN).addScalar("xiaoshou", StandardBasicTypes.BOOLEAN).addScalar("mendianNo", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(MenDian.class));

            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            List<MenDian> list = query.list();
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);
            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);
            json.setResult(list);
            if (null != list && list.size() > 0)
            {
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);
                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS queryMendianPage 方法调用失败，token校验失败");
            }
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoListPage<MenDian> queryMendExtPage(String name , String nickname , Long currentId , int pageSize , String token , Boolean isStation , Boolean weixiu , Boolean xiaoshou , String mac) throws Exception
    {
        VoListPage<MenDian> json = new VoListPage<MenDian>();
        Long fuwuzhanId = getIdFromToken(token, mac);
        if (null != fuwuzhanId)
        {
            if (log.isDebugEnabled())
            {
                log.debug("传入参数 nickname is" + nickname + ", currentId is " + currentId + ",pageSize is " + pageSize);
            }
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            countsql.append("select count(1) as counNum  from  t_MenDian m join t_FuwuZhan f on f.id=m.fuwuzhanId left join t_WeixinInfo  w on w.openid=m.wxid  where 1=1 ");
            sql.append("select m.address, m.city, m.crateDate, m.detailInfo, m.fuwuzhanId, f.name as fuwuzhanName, m.id, m.imageUrl, m.latitude, m.longitude, m.lxr, m.lxrTel, m.name, w.nickname, m.province, m.town, m.updateDate, m.wxid,m.chargeStation,m.chargImageUrl,m.weixiu,m.xiaoshou,m.mobiCharge,m.mendianNo  from  t_MenDian m left join t_FuwuZhan f on f.id=m.fuwuzhanId  left join t_WeixinInfo   w  on w.openid=m.wxid   where 1=1 ");

            sql.append(" and m.status=" + BuzConst.STATUS_YES + " and (1=0 ");
            countsql.append(" and m.status=" + BuzConst.STATUS_YES + " and (1=0  ");

            if ((null == isStation || (!isStation)) && (null == weixiu || (!weixiu)) && (null == xiaoshou || (!xiaoshou)))
            {
                sql.append(" or 1=1 ");
                countsql.append(" or 1=1 ");
            }
            else
            {
                if (null != isStation && isStation)
                {
                    sql.append(" or m.chargeStation=" + isStation + " ");
                    countsql.append(" or m.chargeStation=" + isStation + " ");
                }
                if (null != weixiu && weixiu)
                {
                    sql.append(" or m.weixiu=" + weixiu + " ");
                    countsql.append(" or m.weixiu=" + weixiu + " ");
                }
                if (null != xiaoshou && xiaoshou)
                {
                    sql.append(" or m.xiaoshou=" + xiaoshou + " ");
                    countsql.append(" or m.xiaoshou=" + xiaoshou + " ");
                }
            }
            sql.append(" )");
            countsql.append(" ) ");

            if (!StringUtils.isBlank(nickname))
            {
                sql.append(" and w.nickname  like :nickname");
                countsql.append(" and w.nickname  like :nickname");
            }
            if (null != fuwuzhanId)
            {
                sql.append(" and m.fuwuzhanId= :fuwuzhanId ");
                countsql.append(" and m.fuwuzhanId= :fuwuzhanId ");
            }
            if (!StringUtils.isBlank(name))
            {
                sql.append(" and m.name  like :name");
                countsql.append(" and m.name  like :name");
            }
            if (null != currentId)
            {
                sql.append(" and m.id<:currentId ");
            }
            Session session = getOpenSession();
            query = session.createSQLQuery(sql.toString() + "  order  by m.id  desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("address", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("latitude",
                    StandardBasicTypes.DOUBLE).addScalar("longitude", StandardBasicTypes.DOUBLE).addScalar("lxr", StandardBasicTypes.STRING).addScalar("lxrTel", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("nickname", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("wxid", StandardBasicTypes.STRING).addScalar("mobiCharge",
                    StandardBasicTypes.BOOLEAN).addScalar("chargeStation", StandardBasicTypes.BOOLEAN).addScalar("chargImageUrl", StandardBasicTypes.STRING).addScalar("weixiu", StandardBasicTypes.BOOLEAN).addScalar("xiaoshou", StandardBasicTypes.BOOLEAN).addScalar("mendianNo", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(MenDian.class));

            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            List<MenDian> list = query.list();
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);
            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);
            json.setResult(list);
            if (null != list && list.size() > 0)
            {
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);
                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS queryMendianPage 方法调用失败，token校验失败");
            }
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoListPage<MenDian> queryMendExtenPage(String name , String nickname , Long currentId , int pageSize , String token , Boolean isStation , Boolean weixiu , Boolean xiaoshou , Boolean mobiCharge , String mac) throws Exception
    {
        VoListPage<MenDian> json = new VoListPage<MenDian>();
        Long fuwuzhanId = getIdFromToken(token, mac);
        if (null != fuwuzhanId)
        {
            if (log.isDebugEnabled())
            {
                log.debug("传入参数 nickname is" + nickname + ", currentId is " + currentId + ",pageSize is " + pageSize);
            }
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            countsql.append("select count(1) as counNum  from  t_MenDian m join t_FuwuZhan f on f.id=m.fuwuzhanId left join t_WeixinInfo  w on w.openid=m.wxid  where 1=1 ");
            sql.append("select m.address, m.city, m.crateDate, m.detailInfo, m.fuwuzhanId, f.name as fuwuzhanName, m.id, m.imageUrl, m.latitude, m.longitude, m.lxr, m.lxrTel, m.name, w.nickname, m.province, m.town, m.updateDate, m.wxid,m.chargeStation,m.chargImageUrl,m.weixiu,m.xiaoshou,m.mobiCharge,m.mendianNo  from  t_MenDian m left join t_FuwuZhan f on f.id=m.fuwuzhanId  left join t_WeixinInfo   w  on w.openid=m.wxid   where 1=1 ");

            sql.append(" and m.status=" + BuzConst.STATUS_YES + " and (1=0 ");
            countsql.append(" and m.status=" + BuzConst.STATUS_YES + " and (1=0  ");

            if ((null == isStation || (!isStation)) && (null == weixiu || (!weixiu)) && (null == xiaoshou || (!xiaoshou)) && (null == mobiCharge || (!mobiCharge)))
            {
                sql.append(" or 1=1 ");
                countsql.append(" or 1=1 ");
            }
            else
            {
                if (null != isStation && isStation)
                {
                    sql.append(" or m.chargeStation=" + isStation + " ");
                    countsql.append(" or m.chargeStation=" + isStation + " ");
                }
                if (null != weixiu && weixiu)
                {
                    sql.append(" or m.weixiu=" + weixiu + " ");
                    countsql.append(" or m.weixiu=" + weixiu + " ");
                }
                if (null != xiaoshou && xiaoshou)
                {
                    sql.append(" or m.xiaoshou=" + xiaoshou + " ");
                    countsql.append(" or m.xiaoshou=" + xiaoshou + " ");
                }
                if (null != mobiCharge && mobiCharge)
                {
                    sql.append(" or m.mobiCharge=" + mobiCharge + " ");
                    countsql.append(" or m.mobiCharge=" + mobiCharge + " ");
                }
            }
            sql.append(" )");
            countsql.append(" ) ");

            if (!StringUtils.isBlank(nickname))
            {
                sql.append(" and w.nickname  like :nickname");
                countsql.append(" and w.nickname  like :nickname");
            }
            if (null != fuwuzhanId)
            {
                sql.append(" and m.fuwuzhanId= :fuwuzhanId ");
                countsql.append(" and m.fuwuzhanId= :fuwuzhanId ");
            }
            if (!StringUtils.isBlank(name))
            {
                sql.append(" and m.name  like :name");
                countsql.append(" and m.name  like :name");
            }
            if (null != currentId)
            {
                sql.append(" and m.id<:currentId ");
            }
            Session session = getOpenSession();
            query = session.createSQLQuery(sql.toString() + "  order  by m.id  desc ").addScalar("id", StandardBasicTypes.LONG).addScalar("address", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fuwuzhanName", StandardBasicTypes.STRING).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("latitude",
                    StandardBasicTypes.DOUBLE).addScalar("longitude", StandardBasicTypes.DOUBLE).addScalar("lxr", StandardBasicTypes.STRING).addScalar("lxrTel", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("nickname", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("wxid", StandardBasicTypes.STRING).addScalar("chargeStation",
                    StandardBasicTypes.BOOLEAN).addScalar("mobiCharge", StandardBasicTypes.BOOLEAN)

            .addScalar("chargImageUrl", StandardBasicTypes.STRING).addScalar("weixiu", StandardBasicTypes.BOOLEAN).addScalar("xiaoshou", StandardBasicTypes.BOOLEAN).addScalar("mendianNo", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(MenDian.class));

            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            List<MenDian> list = query.list();
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);
            if (!StringUtils.isBlank(nickname))
            {
                query.setString("nickname", "%" + nickname + "%");
            }
            if (null != fuwuzhanId)
            {
                query.setLong("fuwuzhanId", fuwuzhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);
            json.setResult(list);
            if (null != list && list.size() > 0)
            {
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);
                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS queryMendianPage 方法调用失败，token校验失败");
            }
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoListPage<StatisMendian> queryStaticPage(String sdate , String edate , String name , String changeType , Long currentId , int pageSize , String token , String mac)
    {
        VoListPage<StatisMendian> json = new VoListPage<StatisMendian>();
        Long fuwuzhanId = getIdFromToken(token, mac);
        if (null != fuwuzhanId)
        {
            if (log.isDebugEnabled())
            {
                log.debug("传入参数 sdate is" + sdate + ", edate is " + edate + ",pageSize is " + pageSize);
                log.debug("传入参数 changeType is" + changeType + ", name is " + name + ",currentId is " + currentId);
            }
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            StringBuilder totalsql = new StringBuilder();
            Query query = null;
            Session session = getOpenSession();
            FuwuZhan fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, fuwuzhanId);
            totalsql.append("SELECT sum(usNum) AS usNum,sum(totalNum) AS totalNum,SUM(sum0) AS sum0,  SUM(sum1) AS sum1,SUM(sum2) AS sum2,SUM(sum3) AS sum3,SUM(sum4) AS sum4,SUM(sum5) AS sum5,sum(sum_near) AS sum_near,sum(sum_shm) AS sum_shm,sum(sum_wwd) AS sum_wwd,NUll as mendianId,'总计' AS `name`,null as lxr,NULL as address  FROM(");

            sql.append("SELECT count(userId) AS usNum,sum(totalNum) AS totalNum,SUM(sum0) AS sum0,  SUM(sum1) AS sum1,SUM(sum2) AS sum2,SUM(sum3) AS sum3,SUM(sum4) AS sum4,SUM(sum5) AS sum5,sum(sum_near) AS sum_near,sum(sum_shm) AS sum_shm,sum(sum_wwd) AS sum_wwd,mendianId,`name`,lxr,address  FROM(");
            //处理分配到门店的订单V_FWZ_STATIS_01 是有门店的订单视图
            sql.append("SELECT userId,count(id) AS totalNum,mendianId,`name`, address,lxr,sum(state0) sum0,sum(state1) sum1,sum(state2) sum2,sum(state3) sum3,sum(state4) sum4,sum(state5) sum5,sum(fujin) sum_near,sum(shm) sum_shm,sum(wwd) sum_wwd  FROM V_FWZ_STATIS_01 ");
            sql.append(" WHERE fuwuzhanId=:fuwuzhanId ");
            if (!StringUtils.isBlank(sdate))
            {
                sql.append(" and crateDate>=:sdate ");
            }
            if (!StringUtils.isBlank(edate))
            {
                sql.append(" and crateDate<=:edate ");
            }
            if (!StringUtils.isBlank(changeType))
            {
                sql.append(" and changeType=:changeType ");
            }

            if (!StringUtils.isBlank(name))
            {
                sql.append(" and name like :name");
            }
            sql.append(" GROUP BY address,lxr,`name`,mendianId,userId ");

            if (StringUtils.isBlank(name))
            {
                //处理为分配到门店的订单V_FWZ_STATIS_02 是该类订单视图，该类订单根据服务站区域分配
                sql.append(" UNION SELECT userId,count(id) AS totalNum,mendianId,`name`, address,lxr,sum(state0) sum0,sum(state1) sum1,sum(state2) sum2,sum(state3) sum3,sum(state4) sum4,sum(state5) sum5,sum(fujin) sum_near,sum(shm) sum_shm,sum(wwd) sum_wwd  FROM V_FWZ_STATIS_02  ");
                sql.append(" WHERE 1=1 ");
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    sql.append(" and  province like :province ");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        sql.append(" and city like :city ");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            sql.append(" and town like :town ");
                        }
                    }
                }
                if (!StringUtils.isBlank(sdate))
                {
                    sql.append(" and crateDate>=:sdate2 ");
                }
                if (!StringUtils.isBlank(edate))
                {
                    sql.append(" and crateDate<=:edate2 ");
                }
                if (!StringUtils.isBlank(name))
                {
                    sql.append(" and name like :name2");
                }
                if (!StringUtils.isBlank(changeType))
                {
                    sql.append(" and changeType=:changeType2 ");
                }
                sql.append(" GROUP BY address,lxr,`name`,mendianId,userId");
                //V_FWZ_STATIS_01_s1 视图为每个门店一份空的订单数据
                sql.append(" UNION  SELECT userId,count(id) AS totalNum,mendianId,`name`, address,lxr,sum(state0) sum0,sum(state1) sum1,sum(state2) sum2,sum(state3) sum3,sum(state4) sum4,sum(state5) sum5,sum(fujin) sum_near,sum(shm) sum_shm,sum(wwd) sum_wwd  FROM V_FWZ_STATIS_01_s1 ");

                sql.append(" WHERE fuwuzhanId=:fuwuzhanId2 ");

                sql.append(" GROUP BY address,lxr,`name`,mendianId,userId ");
            }
            countsql.append("select count(*) as counNum from (" + sql + ") r GROUP BY  address,lxr,`name`,mendianId) as result ");

            totalsql.append(sql + ") r   GROUP BY  address,lxr,`name`,mendianId    order  by mendianId ) too  ");
            if (null != currentId)
            {
                sql.append(") r  where mendianId >:currentId  GROUP BY  address,lxr,`name`,mendianId    order  by mendianId");
            }
            else
            {
                sql.append(") r   GROUP BY  address,lxr,`name`,mendianId    order  by mendianId");
            }
            log.debug("门店统计 sql:" + sql);
            query = session.createSQLQuery(sql.toString()).addScalar("address", StringType.INSTANCE).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("lxr", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("totalNum", StandardBasicTypes.INTEGER).addScalar("sum_near", StandardBasicTypes.INTEGER).addScalar("sum_shm", StandardBasicTypes.INTEGER).addScalar("sum_wwd", StandardBasicTypes.INTEGER).addScalar("sum0", StandardBasicTypes.INTEGER).addScalar("sum1",
                    StandardBasicTypes.INTEGER).addScalar("usNum", StandardBasicTypes.INTEGER).addScalar("sum2", StandardBasicTypes.INTEGER).addScalar("sum3", StandardBasicTypes.INTEGER).addScalar("sum4", StandardBasicTypes.INTEGER).addScalar("sum5", StandardBasicTypes.INTEGER).setResultTransformer(Transformers.aliasToBean(StatisMendian.class));
            query.setMaxResults(pageSize);

            query.setLong("fuwuzhanId", fuwuzhanId);

            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }

            if (!StringUtils.isBlank(sdate))
            {
                query.setString("sdate", sdate);
            }
            if (!StringUtils.isBlank(edate))
            {
                query.setString("edate", edate);
            }
            if (!StringUtils.isBlank(changeType))
            {
                query.setString("changeType", changeType);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (StringUtils.isBlank(name))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
                query.setLong("fuwuzhanId2", fuwuzhanId);
                if (!StringUtils.isBlank(sdate))
                {
                    query.setString("sdate2", sdate);
                }
                if (!StringUtils.isBlank(edate))
                {
                    query.setString("edate2", edate);
                }
                if (!StringUtils.isBlank(changeType))
                {
                    query.setString("changeType2", changeType);
                }
                if (!StringUtils.isBlank(name))
                {
                    query.setString("name2", "%" + name + "%");
                }
            }

            List<StatisMendian> list = query.list();
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);

            query.setLong("fuwuzhanId", fuwuzhanId);
            if (!StringUtils.isBlank(sdate))
            {
                query.setString("sdate", sdate);
            }
            if (!StringUtils.isBlank(edate))
            {
                query.setString("edate", edate);
            }
            if (!StringUtils.isBlank(changeType))
            {
                query.setString("changeType", changeType);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }
            if (StringUtils.isBlank(name))
            {
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                        {
                            query.setString("town", fuwuzhan.getTown().replace("县", "").replace("区", "") + "%");
                        }
                    }
                }
                query.setLong("fuwuzhanId2", fuwuzhanId);
                if (!StringUtils.isBlank(sdate))
                {
                    query.setString("sdate2", sdate);
                }
                if (!StringUtils.isBlank(edate))
                {
                    query.setString("edate2", edate);
                }
                if (!StringUtils.isBlank(changeType))
                {
                    query.setString("changeType2", changeType);
                }
                if (!StringUtils.isBlank(name))
                {
                    query.setString("name2", "%" + name + "%");
                }
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);
            json.setResult(list);
            if (null != list && list.size() > 0)
            {
                long id = 0l;
                if (null != (list.get(list.size() - 1).getMendianId()))
                {
                    id = list.get(list.size() - 1).getMendianId();
                }

                json.setCurrentId(id);

                if (null == currentId)
                {
                    query = session.createSQLQuery(totalsql.toString()).addScalar("address", StringType.INSTANCE).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("lxr", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("totalNum", StandardBasicTypes.INTEGER).addScalar("sum_near", StandardBasicTypes.INTEGER).addScalar("sum_shm", StandardBasicTypes.INTEGER).addScalar("sum_wwd", StandardBasicTypes.INTEGER).addScalar("sum0", StandardBasicTypes.INTEGER).addScalar("sum1",
                            StandardBasicTypes.INTEGER).addScalar("usNum", StandardBasicTypes.INTEGER).addScalar("sum2", StandardBasicTypes.INTEGER).addScalar("sum3", StandardBasicTypes.INTEGER).addScalar("sum4", StandardBasicTypes.INTEGER).addScalar("sum5", StandardBasicTypes.INTEGER).setResultTransformer(Transformers.aliasToBean(StatisMendian.class));

                    query.setLong("fuwuzhanId", fuwuzhanId);
                    if (!StringUtils.isBlank(sdate))
                    {
                        query.setString("sdate", sdate);
                    }
                    if (!StringUtils.isBlank(edate))
                    {
                        query.setString("edate", edate);
                    }
                    if (!StringUtils.isBlank(changeType))
                    {
                        query.setString("changeType", changeType);
                    }
                    if (!StringUtils.isBlank(name))
                    {
                        query.setString("name", "%" + name + "%");
                    }
                    if (StringUtils.isBlank(name))
                    {
                        if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                        {
                            query.setString("province", fuwuzhan.getProvince() + "%");
                            if (!StringUtils.isBlank(fuwuzhan.getCity()) && (!"请选择".equals(fuwuzhan.getCity())))
                            {
                                query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                                if (!StringUtils.isBlank(fuwuzhan.getTown()) && (!"请选择".equals(fuwuzhan.getTown())))
                                {
                                    query.setString("town", fuwuzhan.getTown() + "%");
                                }
                            }
                        }
                        query.setLong("fuwuzhanId2", fuwuzhanId);
                        if (!StringUtils.isBlank(sdate))
                        {
                            query.setString("sdate2", sdate);
                        }
                        if (!StringUtils.isBlank(edate))
                        {
                            query.setString("edate2", edate);
                        }
                        if (!StringUtils.isBlank(changeType))
                        {
                            query.setString("changeType2", changeType);
                        }
                        if (!StringUtils.isBlank(name))
                        {
                            query.setString("name2", "%" + name + "%");
                        }
                    }
                    List<StatisMendian> list2 = query.list();
                    if (null != list2 && list2.size() > 0)
                    {
                        list2.addAll(list);
                        json.setResult(list2);
                    }
                    else
                    {
                        json.setResult(list);
                    }
                }

                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("WS queryMendianPage 方法调用失败，token校验失败");
            }
            json.setAuthError();
        }
        return json;
    }

    @SuppressWarnings("unchecked")
    @Override
    public VoBackModel<VoDingDanCard> queryCardOrderById(Long id , String token , String mac)
    {
        VoBackModel<VoDingDanCard> json = new VoBackModel<VoDingDanCard>();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            VoDingDanCard<DingDanCardGoods> m = null;
            Query query = session.createQuery(" from  DingDanCardGoods where fid=:fid");
            query.setLong("fid", id);
            ArrayList<DingDanCardGoods> l = (ArrayList<DingDanCardGoods>) query.list();
            if (null != l && l.size() > 0)
            {
                StringBuilder sql = new StringBuilder();
                sql.append("select d.id,d.addressId,d.carNo,d.dingDanUid,userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
                sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
                sql.append("m.name as mendName,m.imageUrl as mendImgUrl,m.lxr as mendLxr ,m.lxrTel as mendLxTel,m.address as mendAddr,");
                sql.append("f.id as fuwuzhanId,f.name as fwzName ");
                sql.append("from t_dingdan_card_main d  ");
                sql.append("left join t_mendian m on m.id=d.mendianId  ");
                sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  ");
                sql.append("where d.id=:id  ");

                query = session.createSQLQuery(sql.toString()).addScalar("id", StandardBasicTypes.LONG).addScalar("dingDanUid", StandardBasicTypes.STRING).addScalar("userId", StandardBasicTypes.STRING).addScalar("kehuName", StandardBasicTypes.STRING).addScalar("lxTel", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("mendianId", StandardBasicTypes.LONG).addScalar("buyType", StandardBasicTypes.STRING).addScalar("goodsPrice", StandardBasicTypes.DOUBLE)

                .addScalar("servicePrice", StandardBasicTypes.DOUBLE).addScalar("lat", StandardBasicTypes.DOUBLE).addScalar("lng", StandardBasicTypes.DOUBLE).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("state", StandardBasicTypes.STRING).addScalar("province", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("mendName", StandardBasicTypes.STRING).addScalar("mendImgUrl",
                        StandardBasicTypes.STRING).addScalar("mendLxr", StandardBasicTypes.STRING).addScalar("mendLxTel", StandardBasicTypes.STRING).addScalar("mendAddr", StandardBasicTypes.STRING).addScalar("fuwuzhanId", StandardBasicTypes.LONG).addScalar("fwzName", StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(VoDingDanCard.class));
                query.setLong("id", id);
                m = (VoDingDanCard<DingDanCardGoods>) query.uniqueResult();
                if (null != m)
                {
                    m.setAllPrice(BuzConst.add(m.getGoodsPrice(), m.getServicePrice()));
                    m.setInvalidDate(DateUtils.getDatePlusHour(m.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                    m.setGoods(l);
                    json.setSuccess(true);
                    json.setMessage("success");
                    json.setModel(m);
                }
            }
        }
        else
        {
            json.setSuccess(false);
            json.setMessage("非法访问，访问凭证无效");
        }
        return json;
    }

    @SuppressWarnings("unchecked")
    @Override
    public VoListPage<DingDanCard> queryCardOrders(String customerName , String customerTel , String mendianName , String dingDanUid , String state , String buyType , Long currentId , int pageSize , String token , String mac)
    {
        VoListPage<DingDanCard> json = new VoListPage<DingDanCard>();
        if (checkAccess(token, mac))
        {
            FuwuZhan fuwuzhan = null;
            Session session = getOpenSession();
            Long fuwuZhanId = getIdFromToken(token, mac);
            if (null != fuwuZhanId)
            {
                fuwuzhan = (FuwuZhan) session.get(FuwuZhan.class, fuwuZhanId);
            }

            List<DingDanCard> list = new ArrayList<DingDanCard>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            Query query = null;
            sql.append("select d.id,d.addressId,d.carNo,d.dingDanUid,userId,d.kehuName,d.lxTel,d.address,d.mendianId,d.buyType,d.goodsPrice,d.servicePrice, ");
            sql.append("d.lat,d.lng,d.crateDate,d.updateDate,d.state,d.province,d.city,d.town, ");
            sql.append("m.name as mendName,m.imageUrl as mendImgUrl, ");
            sql.append("f.id as fuwuzhanId,f.name as fwzName ");

            sql.append("from t_dingdan_card_main d  ");
            sql.append("left join t_mendian m on m.id=d.mendianId  ");
            sql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id where 1=1 ");

            countsql.append("select count(*) as counNum ");
            countsql.append("from t_dingdan_card_main d  ");
            countsql.append("left join t_mendian m on m.id=d.mendianId  ");
            countsql.append("left join t_fuwuzhan f on m.fuwuzhanId =f.id  where 1=1  ");

            if (!StringUtils.isBlank(dingDanUid))
            {
                sql.append(" and d.dingDanUid like :dingDanUid");
                countsql.append(" and d.dingDanUid like :dingDanUid");
            }
            if (!StringUtils.isBlank(customerName))
            {
                sql.append(" and d.kehuName like :customerName");
                countsql.append(" and d.kehuName like :customerName");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                sql.append(" and d.lxTel like :customerTel");
                countsql.append(" and d.lxTel like :customerTel");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                sql.append(" and m.name like :mendianName");
                countsql.append(" and m.name like :mendianName");
            }
            if (!StringUtils.isBlank(state))
            {
                sql.append(" and d.state=:state");
                countsql.append(" and d.state=:state");
            }
            if (!StringUtils.isBlank(buyType))
            {
                sql.append(" and d.buyType=:buyType");
                countsql.append(" and d.buyType=:buyType");
            }

            if (null != fuwuzhan)
            {
                sql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                countsql.append(" and (m.fuwuzhanId=:fuwuzhanId ");
                if (!StringUtils.isBlank(fuwuzhan.getProvince()) && (!"请选择".equals(fuwuzhan.getProvince())))
                {
                    sql.append(" or (d.buyType<>'" + BuzConst.CARD_BUYTYPE_MD + "' and  ");
                    countsql.append(" or (d.buyType<>'" + BuzConst.CARD_BUYTYPE_MD + "' and  ");
                    sql.append("  d.province like :province");
                    countsql.append("  d.province like :province");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()))
                    {
                        sql.append(" and d.city like :city");
                        countsql.append(" and d.city like :city");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()))
                        {
                            sql.append(" and d.town like :town  ");
                            countsql.append(" and d.town like :town ");
                        }
                    }
                    sql.append(" ))");
                    countsql.append(" ))");
                }
            }
            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);

            if (!StringUtils.isBlank(dingDanUid))
            {
                query.setString("dingDanUid", "%" + dingDanUid + "%");
            }
            if (!StringUtils.isBlank(customerName))
            {
                query.setString("customerName", "%" + customerName.trim() + "%");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                query.setString("customerTel", "%" + customerTel.trim() + "%");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                query.setString("mendianName", "%" + mendianName.trim() + "%");
            }
            if (!StringUtils.isBlank(state))
            {
                query.setString("state", state);
            }
            if (!StringUtils.isBlank(buyType))
            {
                query.setString("buyType", buyType);
            }
            if (null != fuwuzhan)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);
                if (!StringUtils.isBlank(fuwuzhan.getProvince()))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);

            if (null != currentId)
            {
                sql.append(" and d.id<:currentId ");
            }
            query = session.createSQLQuery(sql.toString() + " order by id desc").addEntity(DingDanCard.class);
            if (!StringUtils.isBlank(dingDanUid))
            {
                query.setString("dingDanUid", "%" + dingDanUid.trim() + "%");
            }
            if (!StringUtils.isBlank(customerName))
            {
                query.setString("customerName", "%" + customerName.trim() + "%");
            }
            if (!StringUtils.isBlank(customerTel))
            {
                query.setString("customerTel", "%" + customerTel.trim() + "%");
            }
            if (!StringUtils.isBlank(mendianName))
            {
                query.setString("mendianName", "%" + mendianName.trim() + "%");
            }
            if (!StringUtils.isBlank(state))
            {
                query.setString("state", state);
            }
            if (!StringUtils.isBlank(buyType))
            {
                query.setString("buyType", buyType);
            }
            if (null != fuwuzhan)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);

                if (!StringUtils.isBlank(fuwuzhan.getProvince()))
                {
                    query.setString("province", fuwuzhan.getProvince() + "%");
                    if (!StringUtils.isBlank(fuwuzhan.getCity()))
                    {
                        query.setString("city", fuwuzhan.getCity().replace("市", "") + "%");
                        if (!StringUtils.isBlank(fuwuzhan.getTown()))
                        {
                            query.setString("town", fuwuzhan.getTown() + "%");
                        }
                    }
                }
            }
            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            list = query.list();
            if (null != list && list.size() > 0)
            {
                for (DingDanCard o : list)
                {
                    o.setAllPrice(BuzConst.add(o.getGoodsPrice(), o.getServicePrice()));
                    if (!StringUtils.isBlank(o.getCrateDate()))
                    {
                        o.setInvalidDate(DateUtils.getDatePlusHour(o.getCrateDate(), BuzConst.FORMAT_STRING1, BuzConst.FORMAT_STRING2, BuzConst.HOUR48));
                    }
                }
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);

                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }

            json.setResult(list);
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoBackObj updateCardOrderStatus(Long id , String status , Long shopId , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            String hql = "update DingDanCard set  state=:state  where id=:id";
            if (null != shopId && shopId > 0)
            {
                hql = "update DingDanCard set mendianId=:mendianId,state=:state  where id=:id";
            }
            Query query = session.createQuery(hql);
            query.setLong("id", id);
            if (null != shopId && shopId > 0)
            {
                query.setLong("mendianId", shopId);
            }
            query.setString("state", status);
            Transaction tx = session.beginTransaction();
            query.executeUpdate();
            tx.commit();
            if (session.isOpen())
            {
                session.close();
            }
            obj.setCheckSuccess();
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    @Override
    public VoBackObj addOrUpdateMerchant(Merchants model , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            if (null != model)
            {

                model.setDeldata(false);

                Long fuwuzhanId = getIdFromToken(token, mac);
                model.setFuwuzhanId(fuwuzhanId);
                Transaction tx = session.beginTransaction();
                if (null == model.getId() || 0 == model.getId())
                {
                    if (StringUtils.isBlank(model.getStatus()))
                    {
                        model.setStatus("0");
                    }
                    model.setCrateDate(DateUtils.getCurrDate(null));
                    session.save(model);
                }
                else
                {
                    MerchantsLog log = new MerchantsLog();
                    BeanUtils.copyProperties(model, log);
                    log.setId(null);
                    log.setLogTime(DateUtils.getCurrDate(null));
                    session.save(log);

                    model.setUpdateDate(DateUtils.getCurrDate(null));
                    session.update(model);
                }
                obj.setId(model.getId());
                tx.commit();
                if (session.isOpen())
                {
                    session.close();
                }

                obj.setCheckSuccess();
            }
            else
            {
                obj.setSuccess(false);
                obj.setMessage("model is null");
            }
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }

    @Override
    public VoListPage<Merchants> queryMerchantPage(String name , String lxr , String address , String no , String status , String merchType , Long currentId , int pageSize , String token , String mac)
    {
        VoListPage<Merchants> json = new VoListPage<Merchants>();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Long fuwuZhanId = getIdFromToken(token, mac);
            List<Merchants> list = new ArrayList<Merchants>();
            Query query = null;
            StringBuilder sql = new StringBuilder();
            StringBuilder countsql = new StringBuilder();
            countsql.append("select count(1) as counNum  from t_Merchants m LEFT JOIN t_fuwuzhan f on f.id=m.fuwuzhanId where 1=1 ");
            sql.append(" select  m.id,m.actiAtt,m.actiBeginTime,m.actiEndTime,m.address,m.city,m.crateDate,m.deldata,m.detailInfo,m.fuwuzhanId,m.imageUrl,m.invaliDates,m.keyWords,m.latitude,m.longitude,m.lxr,m.lxrTel,m.name,m.no,m.wxNo,m.province,m.status,m.town, m.type,m.updateDate,m.useRules,m.allowTime,m.wxid,m.reason,m.wxNick,m.xiajiaReason ,f.`name`  fwzName from t_Merchants m LEFT JOIN t_fuwuzhan f on f.id=m.fuwuzhanId where 1=1 ");

            sql.append(" and m.deldata=:deldata  ");
            countsql.append(" and m.deldata=:deldata ");

            if (null != fuwuZhanId)
            {
                sql.append(" and m.fuwuzhanId= :fuwuzhanId ");
                countsql.append(" and m.fuwuzhanId= :fuwuzhanId ");
            }
            if (!StringUtils.isBlank(name))
            {
                sql.append(" and m.name  like :name ");
                countsql.append(" and m.name  like :name ");
            }

            if (!StringUtils.isBlank(lxr))
            {
                sql.append(" and m.lxr  like :lxr ");
                countsql.append(" and m.lxr  like :lxr ");
            }
            if (!StringUtils.isBlank(address))
            {
                sql.append(" and m.address  like :address ");
                countsql.append(" and m.address  like :address ");
            }

            if (!StringUtils.isBlank(no))
            {
                sql.append(" and m.no  like :no ");
                countsql.append(" and m.no  like :no ");
            }

            if (!StringUtils.isBlank(status))
            {
                sql.append(" and m.status=:status ");
                countsql.append(" and  m.status=:status ");
            }

            if (!StringUtils.isBlank(merchType))
            {
                sql.append(" and m.type=:merchType ");
                countsql.append(" and m.type=:merchType ");
            }

            //            query = getCurrentSession().createSQLQuery(sql.toString()).addScalar("id", StandardBasicTypes.LONG).addScalar("actiAtt", StandardBasicTypes.STRING).addScalar("actiBeginTime", StandardBasicTypes.STRING).addScalar("actiEndTime", StandardBasicTypes.STRING).addScalar("address", StandardBasicTypes.STRING).addScalar("city", StandardBasicTypes.STRING).addScalar("crateDate", StandardBasicTypes.STRING).addScalar("deldata", StandardBasicTypes.BOOLEAN).addScalar("detailInfo", StandardBasicTypes.STRING).addScalar(
            //                    "fuwuzhanId", StandardBasicTypes.LONG).addScalar("imageUrl", StandardBasicTypes.STRING).addScalar("invaliDates", StandardBasicTypes.STRING).addScalar("keyWords", StandardBasicTypes.STRING).addScalar("latitude", StandardBasicTypes.DOUBLE).addScalar("longitude", StandardBasicTypes.DOUBLE).addScalar("lxr", StandardBasicTypes.STRING).addScalar("lxrTel", StandardBasicTypes.STRING).addScalar("name", StandardBasicTypes.STRING).addScalar("no", StandardBasicTypes.STRING).addScalar("province",
            //                    StandardBasicTypes.STRING).addScalar("status", StandardBasicTypes.STRING).addScalar("town", StandardBasicTypes.STRING).addScalar("type", StandardBasicTypes.STRING).addScalar("updateDate", StandardBasicTypes.STRING).addScalar("useRules", StandardBasicTypes.STRING).addScalar("wxid", StandardBasicTypes.STRING).addScalar("reason", StandardBasicTypes.STRING).addScalar("wxNick", StandardBasicTypes.STRING).addScalar("xiajiaReason", StandardBasicTypes.STRING).addScalar("fwzName",
            //                    StandardBasicTypes.STRING).setResultTransformer(Transformers.aliasToBean(Merchants.class));

            query = session.createSQLQuery(countsql.toString()).addScalar("counNum", StandardBasicTypes.INTEGER);

            query.setBoolean("deldata", false);

            if (null != fuwuZhanId)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }

            if (!StringUtils.isBlank(lxr))
            {
                query.setString("lxr", "%" + lxr + "%");
            }
            if (!StringUtils.isBlank(address))
            {
                query.setString("address", "%" + address + "%");
            }

            if (!StringUtils.isBlank(no))
            {
                query.setString("no", no + "%");
            }

            if (!StringUtils.isBlank(status))
            {
                query.setString("status", status);
            }

            if (!StringUtils.isBlank(merchType))
            {
                query.setString("merchType", merchType);
            }

            int totalCount = (Integer) query.uniqueResult();
            json.setTotalSize(totalCount);
            json.setPageSize(pageSize);

            if (null != currentId)
            {
                sql.append(" and t.id<:currentId ");
            }
            query = session.createSQLQuery(sql.toString() + " order by id desc").addEntity(Merchants.class);
            query.setBoolean("deldata", false);

            if (null != fuwuZhanId)
            {
                query.setLong("fuwuzhanId", fuwuZhanId);
            }
            if (!StringUtils.isBlank(name))
            {
                query.setString("name", "%" + name + "%");
            }

            if (!StringUtils.isBlank(lxr))
            {
                query.setString("lxr", "%" + lxr + "%");
            }
            if (!StringUtils.isBlank(address))
            {
                query.setString("address", "%" + address + "%");
            }

            if (!StringUtils.isBlank(no))
            {
                query.setString("no", no + "%");
            }
            if (!StringUtils.isBlank(status))
            {
                query.setString("status", status);
            }
            if (!StringUtils.isBlank(merchType))
            {
                query.setString("merchType", merchType);
            }

            if (null != currentId)
            {
                query.setLong("currentId", currentId);
            }
            query.setMaxResults(pageSize);
            list = query.list();
            if (null != list && list.size() > 0)
            {
                long id = list.get(list.size() - 1).getId();
                json.setCurrentId(id);

                if (list.size() < pageSize)
                {//此次查询已经不足1页
                    json.setHasNext(false);
                }
                else if (list.size() == pageSize)
                {
                    if (id <= 1l)
                    {//如果<=1 
                        json.setHasNext(false);
                    }
                    else
                    {
                        log.debug("如果是满的list且最后一记录id不是1，当期还有下一页，下次查询返回null list");
                        json.setHasNext(true);
                    }
                }
                else
                {
                    json.setSuccess(false);
                    log.debug("此信息error");
                }
            }
            else
            {
                json.setSuccess(false);
                json.setHasNext(false);
            }
            json.setResult(list);
            if (session.isOpen())
            {
                session.close();
            }
        }
        else
        {
            json.setAuthError();
        }
        return json;
    }

    @Override
    public VoListPage<Dict> queryMerchantsTypes(@WebParam(name = "token") String token , @WebParam(name = "mac") String mac)
    {
        VoListPage<Dict> vo = new VoListPage<Dict>();
        String hql = "from Dict where title=:title  order by  dictPaixu ";
        Session session = getOpenSession();
        Query q = session.createQuery(hql);
        q.setString("title", BuzConst.MERCHANTS_TITLE);
        List<Dict> l = q.list();
        vo.setResult(l);
        if (null != l && l.size() > 0)
        {
            vo.setTotalSize(l.size());
        }
        vo.setSuccess(true);
        vo.setMessage("");
        return vo;
    }

    @Override
    public VoBackObj deleteMerchant(Long id , String token , String mac)
    {
        VoBackObj obj = new VoBackObj();
        if (checkAccess(token, mac))
        {
            Session session = getOpenSession();
            Transaction tx = session.beginTransaction();
            String hql = "update Merchants set  deldata=:deldata where id=:id ";
            Query q = session.createQuery(hql);
            q.setBoolean("deldata", true);
            q.setLong("id", id);
            int i = q.executeUpdate();
            tx.commit();
            if (session.isOpen())
            {
                session.close();
            }

            obj.setSuccess(true);
            obj.setMessage("成功删除" + i + "条记录");
        }
        else
        {
            obj.setCheckError();
        }
        return obj;
    }
}
